<?php
/**
 * 大赛终审
 */
namespace Beerus\Modules\DesignerCompetition2021\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\DesignerCompetition\DcAward;
use Doraemon\model\DesignerCompetition2021\audit\admin\DcAuditFirstWorkAdmin;
use Doraemon\service\DesignerCompetition2021\Audit;
use Doraemon\service\DesignerCompetition2021\DcAdmin;
use Doraemon\service\DesignerCompetition2021\SignUp;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;

class FinalAuditController extends Controller {
    const PAGE_SIZE = 10;

    public static $dcAuditResultClass = '';
    public static $dcAuditWorkClass = '';

    public function initController($auditStep = 2) {
        $step = $auditStep == Audit::AUDIT_STEP_FIRST ? 'First' : 'Final';
        self::$dcAuditResultClass = "\Doraemon\model\DesignerCompetition2021\audit\DcAudit{$step}Result";
        self::$dcAuditWorkClass = "\Doraemon\model\DesignerCompetition2021\audit\DcAudit{$step}Work";
    }

    /**
     * 大赛初审列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content, $awardType) {
        $this->initController();
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);
        $condition = $this->condition($request->all());
        $condition['data_status'] = self::$dcAuditWorkClass::STATUS_NORMAL;
        $condition['award_type'] = $awardType;

        $tab = new Tab();
        $tab->addLink('终筛确认（户型）', '/admin/DesignerCompetition2021/final_audit/1', $awardType == DcAdmin::AUDIT_AWARD_TYPE_HOUSE);
        $tab->addLink('终筛确认（平面）', '/admin/DesignerCompetition2021/final_audit/2', $awardType == DcAdmin::AUDIT_AWARD_TYPE_PLANE);
        $tab->addLink('终筛确认（软装）', '/admin/DesignerCompetition2021/final_audit/3', $awardType == DcAdmin::AUDIT_AWARD_TYPE_SOFT);
        $tab->addLink('终筛确认（材料/工艺）', '/admin/DesignerCompetition2021/final_audit/4', $awardType == DcAdmin::AUDIT_AWARD_TYPE_MAKE);
        $tab->addLink('终筛确认（生活解决）', '/admin/DesignerCompetition2021/final_audit/5', $awardType == DcAdmin::AUDIT_AWARD_TYPE_LIFE);
        return $content
            ->header('大赛终审列表')
            ->body($tab)
            ->row(self::indexGrid($condition, $page, $pageSize));
    }

    public function indexGrid($condition, $page, $pageSize) {
        $total = self::$dcAuditWorkClass::countListByCondition($condition, '*', Audit::AUDIT_STEP_FINAL);
        $list = self::$dcAuditWorkClass::getListByCondition($condition, $page, $pageSize, Audit::AUDIT_STEP_FINAL);
        if (!empty($list)) {
            Audit::adminFormatAuditList($list, Audit::AUDIT_STEP_FINAL);
        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => self::PAGE_SIZE,
        ]);

        // 获取单项奖
        $awardList = DcAward::getAllAwardListByAwardYear(SignUp::SIGN_YEAR);
        $awardSelectList = [];
        foreach ($awardList as $awardItem) {
            if ($awardItem['award_type'] == SignUp::AWARD_TYPE_LIST['house_award']) {
                $awardSelectList['house_award'][$awardItem['id']] = $awardItem['award_show_name'];
                continue;
            }
            if ($awardItem['award_type'] == SignUp::AWARD_TYPE_LIST['single_award']) {
                $awardSelectList['single_award'][$awardItem['id']] = $awardItem['award_show_name'];
                continue;
            }
            if ($awardItem['award_type'] == SignUp::AWARD_TYPE_LIST['brand_award']) {
                $awardSelectList['brand_award'][$awardItem['id']] = $awardItem['award_show_name'];
            }
        }
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $awardSelectList) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
//
                $grid->filter(function (Grid\Filter $filter) use ($awardSelectList) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) use ($awardSelectList) {
                        $filter->equal('uid', '设计师UID');
                        $filter->equal('user_type', '用户身份')->select(DcAdmin::USER_TYPE_MAP);
                        $filter->equal('competition_area', '赛区')->select(DcAdmin::COMPETITION_AREA_NAME);
                        $filter->equal('house_award', '户型')->select($awardSelectList['house_award']);
                        $filter->equal('audit_status', '评审结果')->select(DcAdmin::ADMIN_AUDIT_STATUS_MAP);
                    });

                    $filter->column(1 / 2, function ($filter) {
                        $options = ['' => '全部', '1' => '是', '2' => '否'];
                        $filter->equal('is_remark', '包含备注')->radio($options);
                        $filter->equal('admin_remark', '备注内容');
                        $filter->equal('recommend_cnt', '评审总推荐次数');
                        $filter->equal('pend_cnt', '评审总待定次数');
                        $filter->equal('sign_id', '报名id');
                    });
                    $filter->expand();
                });
//
                $grid->column('sign_id', '报名id')->width(70);
                $grid->column('user_info', '用户信息')->width(140)->display(function () {
                    $userInfo[] = 'uid：' . $this->uid;
                    $userInfo[] = '昵称：<a href="https://frieza.haohaozhu.me/admin/user/Detail/' . $this->uid . '" target="_blank">' . $this->nick . '</a>';
                    $userInfo[] = '身份：' . $this->user_type;
                    return implode('<br/>', $userInfo);
                });
//
                $grid->column('competition_info', '参赛信息')->width(240)->display(function () {
                    $competition_info[] = '城市：' . $this->city;
                    $competition_info[] = '户型：' . $this->house_type;
                    $competition_info[] = '软装：' . $this->is_sign_soft;
                    $competition_info[] = '平面：' . $this->is_sign_plane;
                    $competition_info[] = '报名时间：' . $this->sign_time;
                    return implode('<br/>', $competition_info);
                });
//
                $grid->column('work_link', '作品链接')->width(210)->display(function () {
                    $open = isset($this->work_name) ? '<a class="fa " href="javascript:layer.open(
                        {
                            type: 2,
                            title: \'预览\', 
                            maxmin: true, 
                            area: [\'350px\', \'700px\'],
                            fixed: false,
                            offset: \'r\',
                            content: \'' . $this->link . '\' 
                        });">' . htmlentities($this->work_name) . '</a>' : "";
                    $img = "<img width='200' height='200' src='{$this->work_pic_url}'>";
                    return implode('<br/>', [$img, $open]);

                });
                $grid->column('work_info', '作品信息')->width(300)->display(function () {
                    $work_info = [];
                    $work_info[] = '居室：' . DcAdmin::ROOM_NUM_TYPE_NAME[$this->room_num_type];
                    $work_info[] = '总造价：' . $this->total_price . '万元';
                    $work_info[] = '地区：' . $this->house_area;
                    $work_info[] = '常住人口：' . $this->people_scale;
                    $work_info[] = '项目完成时间：' . $this->finish_date;
                    $work_info[] = '使用面积：' . $this->house_space . '平米';
                    $work_info[] = '合作机构：' . ($this->recommend_organ ? DcAdmin::RECOMMEND_ORGAN_LIST[$this->recommend_organ] : '无');
                    return implode('<br/>', $work_info);
                });
//
                $grid->column('first_audit_list', '初筛成绩')->width(300)->display(function () {
                    if ($this->first_audit_list) {
                        foreach ($this->first_audit_list as $auditItem) {
                            $firstAuditList[] = $auditItem['reviewer_name'] . '：' . $auditItem['audit_status'];
                        }
                        return implode('<br/>', $firstAuditList);
                    }
                });
                $grid->column('final_audit_list', '终筛成绩')->width(300)->display(function () {
                    if ($this->final_audit_list) {
                        foreach ($this->final_audit_list as $auditItem) {
                            $finalAuditList[] = $auditItem['reviewer_name'] . '：' . $auditItem['audit_status'];
                        }
                        return implode('<br/>', $finalAuditList);
                    }
                });
                $grid->column('audit_status', '评审结果')->width(200)->radio(DcAdmin::ADMIN_AUDIT_STATUS_MAP);
                $grid->column('admin_remark', '备注')->width(200)->editable();
                $grid->disableActions();
            }
        );

        return $gridList;
    }

    private function condition($request) {
        $this->initController();
        $response = [];
        if (!empty($request['uid'])) {
            $response['uid'] = $request['uid'];
        }
        if (!empty($request['user_type'])) {
            $response['user_type'] = $request['user_type'];
        }
        if (!empty($request['sign_id'])) {
            $response['sign_id'] = $request['sign_id'];
        }
        if (!empty($request['competition_area'])) {
            $response['competition_area'] = $request['competition_area'];
        }
        if (!empty($request['house_award'])) {
            $response['house_award'] = $request['house_award'];
        }
        if (isset($request['audit_status']) && $request['audit_status'] !== '') {
            $response['audit_status'] = $request['audit_status'];
        }
        // '' = 全部；1=有备注；2=没有备注
        if (!empty($request['is_remark'])) {
            $response['is_remark'] = $request['is_remark'];
        }
        if (!empty($request['admin_remark'])) {
            $response['admin_remark'] = $request['admin_remark'];
        }
        if (isset($request['recommend_cnt']) && $request['recommend_cnt'] !== '') {
            $response['recommend_cnt'] = $request['recommend_cnt'];
        }
        if (isset($request['recommend_cnt']) && $request['pend_cnt'] !== '') {
            $response['pend_cnt'] = $request['pend_cnt'];
        }
        return $response;
    }

    public function save(Request $request, $awardType, $id) {
        $this->initController();
        $pjax = true;
        $status = true;
        $name = $request->input('name');
        $value = $request->input('value');
        $auditStatus = $request->input('audit_status');

        $message = "修改成功";
        try {
            if (isset($name) && isset($value)) {
                switch ($name) {
                    case 'admin_remark':
                        $pjax = false;
                        if (mb_strlen($value) > 300) {
                            throw new \Exception('最多300字');
                        }
                        self::$dcAuditWorkClass::update(['admin_remark' => $value], ['id' => $id]);
                        break;
                    default:
                        throw new \Exception('未开发功能');
                }
            } elseif (isset($auditStatus)) {
                self::$dcAuditWorkClass::update(['audit_status' => $auditStatus], ['id' => $id]);
            } else {
                throw new \Exception('缺少参数错误');
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();

            if (!$pjax) {
                return response()->json(['errors' => [$message]], 422);
            }
        }

        return response()->json(compact('message', 'status'));
    }
}
